import { ref } from 'vue'
import * as echarts from 'echarts'

export function useMemberCompositionChart() {
	const memberCompositionChart = ref(null)

	// 初始化图表的通用函数
	const initChart = (chartRef, option) => {
		if (!chartRef.value) return
		const chart = echarts.init(chartRef.value)
		chart.setOption(option)

		// 添加响应式调整
		window.addEventListener('resize', () => {
			chart.resize()
		})

		return chart
	}

	// 图表2：党员构成分析 - 柱状图
	const initMemberCompositionChart = async (data) => {
		// 从data中使用for提取educationTypes, maleData, femaleData
		// 学历类型需要映射一下
		// 0-大专以下，1-大专，2-本科，3-硕士，4-博士
		// 先排序，确保顺序是0-大专以下，1-大专，2-本科，3-硕士，4-博士
		data.sort((a, b) => a.educationTypes - b.educationTypes);
		let educationTypes = [];
		let maleData = [];
		let femaleData = [];
		for (let item of data) {
			switch (item.educationTypes) {
				case 0: educationTypes.push('大专以下'); break;
				case 1: educationTypes.push('大专'); break;
				case 2: educationTypes.push('本科'); break;
				case 3: educationTypes.push('硕士'); break;
				case 4: educationTypes.push('博士'); break;
				default: educationTypes.push('未知'); break;
			}
			maleData.push(item.maleData);
			femaleData.push(item.femaleData);
		}

		const option = {
			tooltip: {
				trigger: 'axis',
				backgroundColor: 'rgba(0, 0, 0, 0.7)',
				borderColor: '#1890ff',
				textStyle: { color: '#fff' }
			},
			legend: {
				data: ['男性', '女性'],
				textStyle: { color: '#fff', fontSize: 12 },
				top: 0
			},
			grid: {
				left: '3%',
				right: '4%',
				bottom: '10%',
				top: '15%',
				containLabel: true
			},
			xAxis: {
				type: 'category',
				data: educationTypes,
				axisLabel: { color: '#fff', fontSize: 11 },
				axisLine: { lineStyle: { color: 'rgba(64, 158, 255, 0.3)' } }
			},
			yAxis: {
				type: 'value',
				axisLabel: { color: '#fff', fontSize: 11 },
				axisLine: { lineStyle: { color: 'rgba(64, 158, 255, 0.3)' } },
				splitLine: { lineStyle: { color: 'rgba(64, 158, 255, 0.1)' } }
			},
			series: [
				{
					name: '男性',
					type: 'bar',
					data: maleData,
					itemStyle: { color: '#1890ff' }
				},
				{
					name: '女性',
					type: 'bar',
					data: femaleData,
					itemStyle: { color: '#ff7875' }
				}
			]
		}

		initChart(memberCompositionChart, option)
	}

	return {
		memberCompositionChart,
		initMemberCompositionChart
	}
}